from rest_framework import serializers
from django_redis import get_redis_connection
from oauth.utils import check_save_user_token
from users.models import User
from oauth.models import OAuthQQUser

class AuthQQUserSerialzier(serializers.Serializer):

    # Modelserializer没有优势
    #     class Meta:
    #             model=OAuthQQUser
    #             fields=['sms_code','username','openid','password']


    access_token = serializers.CharField(label='操作凭证')
    # 有某些特殊规则时使用正则(营业执照)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')


    def validate(self, attrs):
        """
        获取数据库的openid  sms_code
        获取前段传递的openid  sns_code
        二者进行比较
        判断用户是否存在
            如果存在,校验密码
            如果不存在,则创建新用户
        :param attrs:
        :return:
        """
        #open_id验证
        #获取前端传递的openid
        print(attrs)
        access_token = attrs.get('access_token')
        #获取数据库的openid
        # open_id = get_redis_connection('openid')
        #解密前端openid
        openid = check_save_user_token(access_token)

        #二者比较验证openid是否正确
        if openid is None:
            raise serializers.ValidationError("token被篡改")
        attrs["openid"] = openid

        #sms_code验证
        # 获取数据库sms_code
        mobile = attrs.get('mobile')
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get("sms_%s"%mobile)
        # 获取前端传递的 sms_code
        sms_code = attrs.get('sms_code')
        # 二者进行比较
        if redis_code is None:
            raise serializers.ValidationError("短信验证码已过期")
        if redis_code.decode() != sms_code:
            return serializers.ValidationError("短信验证码错误")
        # 判断用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
            # 如果存在, 校验密码
        else:
            password = attrs.get("password")
            if not user.check_password(password):
                raise  serializers.ValidationError("密码错误")
                # 如果不存在, 则创建新用户
            attrs["user"] =user
            #创建用户
        return attrs

    def create(self, validated_data):
        #获取注册用户
        user = validated_data.get('user')
        # openid = validated_data.get('openid')
        # if not user:
        if user is None:
            user = User.objects.create(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],
            )
        user.set_password(validated_data['password'])
        user.save()
        #绑定openid
        qquser = OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )

        return qquser

















